package com.bric.cacheFile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Queue;

import org.apache.log4j.Logger;

import com.bric.util.StaticStr;

public class Cache2Ftp extends Thread{
	private static final Logger log=Logger.getLogger(Cache2Ftp.class);
	Queue<File> cacheFilequeue=CacheFileScheduled.cacheFilequeue;
	@Override
	public void run() {
		while(cacheFilequeue.size()>0){
			File file=cacheFilequeue.poll();
			String absolutepath=file.getAbsolutePath();
			log.info("文件全名称是"+absolutepath);
			String relativePath=absolutepath.substring((StaticStr.localFilePath+StaticStr.cacheFilePath).length());
//			FtpUpload.upload(ip, port, userName, password, file, remotePathName, remoteName);
			int index=relativePath.lastIndexOf(File.separator);
			String remotePathName=null;
			if(index==-1){
				remotePathName="";
			}else{
				remotePathName=relativePath.substring(0, relativePath.lastIndexOf(File.separator));
				remotePathName=remotePathName.replaceAll("\\\\", "/");
			}
			int port=21;
			try {
				port=Integer.parseInt(StaticStr.finalFtpPort);
			} catch (Exception e) {
				log.info("端口非int值");
			}
//			FtpUpload.upload(StaticStr.finalFtpIp, port, StaticStr.finalFtpUser, StaticStr.finalFtpPassword, file, remotePathName, file.getName());
			copy2FtpPath(StaticStr.finalFtpRoot+StaticStr.finalFileRoot+remotePathName,file);
			log.info("相对文件路径==="+relativePath+"   文件夹"+remotePathName);
//			System.out.println(Thread.currentThread().getName()+"  "+file.getName());
		}
	}
	private void copy2FtpPath(String ftpPath, File file) {
		File targetDir=new File(ftpPath);
		File targetFile=new File(ftpPath+"/"+file.getName());
		log.info("文件地址是"+ftpPath+file.getName());
		if(!targetDir.exists()){
			targetDir.mkdirs();
		}
		log.info(targetFile.getAbsolutePath());
		try (BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(targetFile));BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file))){
			byte[] bytes=new byte[1024];
			int len=0;
			while((len=bis.read(bytes))!=-1){
				bos.write(bytes, 0, len);
			}
			log.info("写入文件成功");
		} catch (Exception e) {
			log.info("读写文件出现异常"+e.getMessage());
		}
	}
}
